package com.power.project.utils;

import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import javax.persistence.Query;
import java.math.BigInteger;
import java.util.Collections;
import java.util.List;

/**
 * @Author mrzhao
 * @CreateDate 2024/6/26 12:26
 * @Desc TODO
 * @Version 1.0
 */
public class PageHelperUtil {
    public static <T> Page<T> getPage(Pageable pageable, Query dataQuery, Query countQuery, Class<T> tClass) {
        //设置分页
        dataQuery.setFirstResult((int) pageable.getOffset());
        dataQuery.setMaxResults(pageable.getPageSize());
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        long total = count.longValue();
        NativeQueryImpl nativeQuery = dataQuery.unwrap(NativeQueryImpl.class);
//        nativeQuery.addScalar()
        nativeQuery.setResultTransformer(Transformers.aliasToBean(tClass));

        List<T> content = total > pageable.getOffset() ?
                dataQuery.getResultList() : Collections.emptyList();

        return new PageImpl<>(content, pageable, total);
    }
}
